import os,json
from django.http.response import HttpResponse,JsonResponse
import requests 
import random
import socket 
from django.db import connections
import logging 
from django.core.cache import caches

logger = logging.getLogger(__name__)

def demo(request):
    
    RANDOM_NUMBER = random.randint(0,5)
    

    result = socket.getfqdn(socket.gethostname())
    CONFIG = os.environ.get('CONFIG','[]')
    logger.info(f'{CONFIG} config')
    for item in json.loads(CONFIG):
        REQUEST = item.get('REQUEST')
        ENDPOINT=item.get('ENDPOINT')
        REQUEST_BODY=item.get('REQUEST_BODY')
        DBUSER=os.environ.get('DBUSER')
        REDIS_PASS=os.environ.get('REDIS_PASS')

        logger.info(f'{ENDPOINT} endpoint')
        logger.info(f'{REQUEST} request')
        logger.info(f'{REQUEST_BODY} request body')
        logger.info(f'{DBUSER} user')
        logger.info(f'{REDIS_PASS} redis pass')


        if REQUEST:
            logger.info("存在REQUEST")
            data = requests.get(ENDPOINT).json()
            result += " > " + data['data']

         
        if REQUEST_BODY:
            result += " > " + str(REQUEST_BODY['data'])
        

        logger.info(f'{DBUSER} user')
        if DBUSER:
            logger.info("存在mysql")
            connection = connections['default']
            with connection.cursor() as cursor:
                cursor.execute(f'select SLEEP({RANDOM_NUMBER})')
                cursor.execute(f'SELECT {RANDOM_NUMBER}')
                data = cursor.fetchone()[0]
                logger.info(f" cursor return {data}")
                result += " > mysql:" + str(data)

        logger.info(f'{REDIS_PASS} redis')
        if REDIS_PASS:
            logger.info("存在redis")
            cache1 = caches['default']
            if cache1.has_key('data'):
                result += " > redis:" + str(cache1.incr('data'))
            else:
                cache1.set('data', 0)
                result += " > redis:" + str(0)

    return JsonResponse({"data": result})

